import { useRef, useState } from "react";
import { AgentRes } from "@/types/agentType";
import { Button, Cell, Field, Form, Input, List, Textarea, Toast, Uploader } from "@taroify/core";
import { BaseEventOrig, View } from "@tarojs/components";
import { chooseImage } from "@tarojs/taro"; // 引入 chooseImage API

export default function Index(props: {agent: AgentRes }) {
  const { name, description, cover_image, welcome_info, sample_query } = props.agent;

  // 用于管理表单输入的状态
  const [formData, setFormData] = useState({
    cover_image: cover_image || "",
    name: name || "",
    description: description || "",
    welcome_info: welcome_info || "",
    sample_query: sample_query || []
  });

  const itemRef = useRef<any>();

  // 处理表单提交
  const onSubmit = (event: BaseEventOrig<any>) => {
    Toast.open("表单提交成功：" + JSON.stringify(event.detail.value));
  };

  // 图片上传处理
  const onUpload = () => {
    chooseImage({
      count: 1, // 只选择一张图片
      sizeType: ["original", "compressed"], // 图片类型
      sourceType: ["album", "camera"], // 图片来源（相册或相机）
    }).then(({ tempFiles }) => {
      setFormData({
        ...formData,
        cover_image: tempFiles[0].path,
      });
    });
  };

  // 处理字段更改
  const handleFieldChange = (field: string, value: any) => {
    setFormData({
      ...formData,
      [field]: value,
    });
  };

  // 渲染引导题输入框
  const renderSampleQueries = () => {
    return formData.sample_query.map((item: string, index: number) => (
      <Cell key={index}>
        <Textarea
          value={item}
          onInput={(e) => handleSampleQueryChange(index, e.detail.value)}
          placeholder="请输入引导题"
        />
      </Cell>
    ));
  };

  // 处理引导题变化
  const handleSampleQueryChange = (index: number, value: string) => {
    const updatedQueries = [...formData.sample_query];
    updatedQueries[index] = value;
    setFormData({
      ...formData,
      sample_query: updatedQueries,
    });
  };

  return (
    <Form onSubmit={onSubmit}>
      {/* Toast 提示 */}
      <Toast id="toast" />

      {/* 表单内容区域 */}
      <Cell.Group inset>
        {/* 封面图片上传 */}
        <Field name="cover_image" label="封面图片" ref={itemRef}>
          <Uploader onUpload={onUpload} />
        </Field>

        {/* 名称输入 */}
        <Field
          name="name"
          label={{ align: "left", children: "名称" }}
          rules={[{ required: true, message: "请填写名称" }]}
        >
          <Input
            value={formData.name}
            onInput={(e) => handleFieldChange("name", e.detail.value)}
            placeholder="请输入名称"
          />
        </Field>

        {/* 描述输入 */}
        <Field
          name="description"
          label={{ align: "left", children: "描述" }}
          rules={[{ required: true, message: "请填写描述" }]}
        >
          <Textarea
            value={formData.description}
            onInput={(e) => handleFieldChange("description", e.detail.value)}
            autoHeight
            placeholder="请输入描述"
          />
        </Field>
      </Cell.Group>

      {/* 欢迎信息输入 */}
      <Field
        name="welcome_info"
        label={{ align: "left", children: "开场白" }}
        rules={[{ required: true, message: "请填写开场白" }]}
      >
        <Textarea
          value={formData.welcome_info}
          onInput={(e) => handleFieldChange("welcome_info", e.detail.value)}
          autoHeight
          placeholder="请输入开场白"
        />
      </Field>

      {/* 引导题输入 */}
      <Field
        name="sample_query"
        label={{ align: "left", children: "引导题" }}
        rules={[{ required: true, message: "请填写引导题" }]}
      >
        <List>{renderSampleQueries()}</List>
      </Field>

      {/* 提交按钮 */}
      <View style={{ margin: "16px" }}>
        <Button shape="round" block color="primary" formType="submit">
          提交
        </Button>
      </View>
    </Form>
  );
}
